import {bodyParser, EventEmitter, express} from "../node-test";
import utils from './utils';
import log from "./logger";
import {Plate} from "./interfaces";
import player from "./player";

const app = express()

class PlateImpl extends EventEmitter implements Plate {
    waitTrigger = false
    lastTimestamp = new Date().getTime()
    available: boolean = false

    constructor() {
        super();
    }

    manualTrigger(isTriger: boolean): void {
        this.waitTrigger = isTriger
    }

    init() {
        log.info('start_server start')
        app.use(bodyParser.json({limit: '10mb'})); // for parsing application/json

        app.post('/comet', (req: any, res: any) => {
            // log.info("comet")
            res.send({
                "Response_AlarmInfoPlate": {
                    "info": "",
                    "channelNum": 0,
                    "manualTrigger": this.waitTrigger ? "ok" : ""
                }
            })
        })

        app.post('/vnl', (req: any, res: any) => {
            // log.info('PlateResult:', req.body.AlarmInfoPlate.result.PlateResult)
            // 重置最近一次连接时间
            this.lastTimestamp = new Date().getTime()
            this.available = true
            const deviceName = req.body.AlarmInfoPlate.deviceName
            const PlateResult = req.body.AlarmInfoPlate.result.PlateResult
            if (utils.isVehicleNumber(PlateResult.license)) {
                if (PlateResult.confidence && parseInt(PlateResult.confidence) > 60) {
                    this.emit("plate", PlateResult.license, deviceName.split("-")[1])
                }
                log.info(deviceName, '车号:', PlateResult.license, '辨识度:', PlateResult.confidence)
                // } else {
                // log.info(deviceName, '车号:', PlateResult.license, '辨识度:', PlateResult.confidence, "车号识别错误")
            }
            res.send('ok')
        })
        app.listen(8888, () => log.info('Plate server listening on port 8888'))
        // 设置定时器
        setInterval(() => {
            const currentTimestamp = new Date().getTime()
            // 60秒没数据就变0
            if (currentTimestamp - this.lastTimestamp > 20 * 1000) {
                this.available = false
            }
        }, 5 * 1000)
    }
}

const plate = new PlateImpl();

export default plate;